from datetime import datetime
from typing import Any, Optional
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
import requests
from app.api import deps
from app.core.config import settings
from app.models.user_model import User
from app.schemas.wechat import WechatLoginRequest, WechatLoginResponse, WechatUserInfo
from app.schemas.user import UserInfoRequest

router = APIRouter()

class WechatAPI:
    def __init__(self):
        self.app_id = settings.WECHAT_APP_ID
        self.app_secret = settings.WECHAT_APP_SECRET
        self.code2session_url = "https://api.weixin.qq.com/sns/jscode2session"
    
    def code2session(self, code: str) -> dict:
        """通过code获取openid和session_key"""
        params = {
            "appid": self.app_id,
            "secret": self.app_secret,
            "js_code": code,
            "grant_type": "authorization_code"
        }
        response = requests.get(self.code2session_url, params=params)
        return response.json()

wechat_api = WechatAPI()

@router.post("/login", response_model=WechatLoginResponse)
async def wechat_login(
    *,
    db: Session = Depends(deps.get_db),
    code: str
) -> Any:
    """
    微信登录
    """
    # 获取session信息
    session_info = wechat_api.code2session(code)
    if "errcode" in session_info:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"WeChat login failed: {session_info['errmsg']}"
        )

    openid = session_info.get("openid")
    if not openid:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Failed to get openid from WeChat"
        )

    # 查找或创建用户
    user = db.query(User).filter(User.openid == openid).first()
    if not user:
        user = User(openid=openid)
        db.add(user)
        db.commit()
        db.refresh(user)

    return WechatLoginResponse(
        code=0,
        message="success",
        data={"user_id": user.id}
    )

@router.get("/userinfo", response_model=WechatUserInfo)
def get_wechat_userinfo(
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """
    获取微信用户信息
    """
    return {
        "id": current_user.id,
        "openid": current_user.openid,
        "nickname": current_user.nickname,
        "avatar_url": current_user.avatar_url,
        "phone": current_user.phone,
        "location": current_user.location,
    }

@router.put("/userinfo")
async def update_userinfo(
    *,
    db: Session = Depends(deps.get_db),
    user_info: UserInfoRequest,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """
    更新用户信息
    """
    current_user.nickname = user_info.nickname
    current_user.avatar_url = user_info.avatar_url
    db.add(current_user)
    db.commit()
    db.refresh(current_user)
    return {"code": 0, "message": "success"} 